from django.shortcuts import render

from commonTool.ApiResponse import api_response
from commonTool.logs.logs_wrapper import LogUtil
from manager.domain.api.manager_api import EventMessagePushApi
from page.function.entity.Menu import Menu
from page.index.req.uploadEventAO import UploadEventAO

# Create your views here.
logs = LogUtil()
resultVO = api_response()


def index(request):
    return resultVO.new_success(data='hello world')


@logs
def menu(request):
    menu_results = Menu.objects.filter(enable=0, del_flag=0).order_by('created')
    menus = list(menu_results.values())
    return resultVO.new_success(data=menus)


@logs
def process_event_message(request):
    print('process_event_message')
    if request.method == 'POST':
        serializer = UploadEventAO(data=request.POST)
        if serializer.is_valid():
            report_text = serializer.validated_data['report_text']
            is_sign = serializer.validated_data['is_sign']
            env = serializer.validated_data['env']
            match_mode = serializer.validated_data['match_mode']
            sn = serializer.validated_data['sn']
            secret = serializer.validated_data['secret']
            up_time = serializer.validated_data['up_time']
            start_key = serializer.validated_data['start_key']
            end_key = serializer.validated_data['end_key']
            if match_mode == 'logs':
                EventMessagePushApi.start_log(message=report_text, is_sign=is_sign, env=env, up_time=up_time)
            elif match_mode == 'custom':
                EventMessagePushApi.start_custom(message=report_text, is_sign=is_sign, env=env, up_time=up_time,
                                                 start_key=start_key, end_key=end_key)
            else:
                EventMessagePushApi.start_all(message=report_text, is_sign=is_sign, env=env, up_time=up_time)

    return resultVO.new_success()


@logs
def upgrade(request):
    return __iframe(request, 'upgrade.html')


@logs
def upload(request):
    return __iframe(request, 'upload.html')


@logs
def powerset(request):
    return __iframe(request, 'powerset.html')


def __iframe(request, url):
    response = render(request, url)
    # 支持内嵌
    response['X-Frame-Options'] = 'ALLOWALL'
    return response
